package htmodels

import (
	"github.com/astaxie/beego/orm"
	"shuxianghui/models"
)

func HTCityAdd(city *models.City) error {
	o := orm.NewOrm()
	_, err := o.Insert(city)
	return err
}

func HTCityGetDetail(city *models.City) error {
	o := orm.NewOrm()
	return o.Read(city)
}

func HTCityGetCount(search string, searchFiled string) (int64, error) {
	o := orm.NewOrm()
	m := models.City{}
	count, err := o.QueryTable(m.TableName()).Filter(searchFiled + "__icontains", search).Count()
	return count, err
}

func HTCityGetList(citys *[]models.City, fields []string, offset int64, limit int, search string, searchFiled string, orderby string) error {
	o := orm.NewOrm()
	m := models.City{}
	_, err := o.QueryTable(m.TableName()).Filter(searchFiled + "__icontains", search).OrderBy(orderby).Offset(offset).Limit(limit).All(citys, fields...)
	return err
}

func HTCityDelete(Ids []int64) (int64, error) {
	o := orm.NewOrm()
	m := models.City{}
	count, err := o.QueryTable(m.TableName()).Filter("Virtural", 0).Filter("Id" + "__in", Ids).Delete()
	return count, err
}

func HTCityUpdate(city *models.City) error {
	o := orm.NewOrm()
	_, err := o.Update(city)
	return err
}

func HTCityGetName(id int) string {
	o := orm.NewOrm()
	city := models.City{Id:id}
	o.Read(&city)
	return city.CityName
}

func HTCityGetProvince(dushuhuiName string) (err error, norow bool, cityid int) {
	o := orm.NewOrm()
	m := models.City{}
	err = o.QueryTable(m.TableName()).Filter(m.FN_CityName() + "__icontains", dushuhuiName).One(&m)
	if err == orm.ErrNoRows {
		return nil, true, 0
	}
	norow = false
	cityid = m.Id
	return
}

func HTCityGetAdminCitiesByUserId(citys *[]models.City, userid int) error {
	o := orm.NewOrm()
	m := models.City{}
	_, err := o.QueryTable(m.TableName()).Filter(m.FN_ManageAdmin(), userid).All(citys)
	return err
}

func HTCityChangeAdminCitiesByUserId(cityIds []int, userid int) error {
	o := orm.NewOrm()
	m := models.City{}
	_, err := o.QueryTable(m.TableName()).Filter(m.FN_Id() + "__in", cityIds).Update(orm.Params{
		m.FN_ManageAdmin(): userid,
	})
	return err
}